package com.itcast.controller;

import com.github.pagehelper.PageInfo;
import com.itcast.dto.TechnicianQuery;
import com.itcast.entity.Technician;
import com.itcast.service.TechnicianService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/technicians")
@Slf4j
public class TechnicianController {

    @Value("${file.upload-dir}")
    private String uploadDir;

    @Autowired
    private TechnicianService technicianService;

    //表单信息 文件上传提交
    //127.0.0.1:9001/api/technicians/upload
    @PostMapping("/upload")
    public ResponseEntity<?> createTechnician(
            @RequestParam String name,
            @RequestParam String phone,
            @RequestParam String message,
            @RequestParam MultipartFile mainImg,
            @RequestParam MultipartFile listImg) {  // 修正参数名：listing → listImg

        try {
            // 1. 校验必填字段
            if (name == null || name.trim().isEmpty()) {
                return ResponseEntity.badRequest().body("姓名不能为空");
            }
            if (phone == null || phone.trim().isEmpty()) {
                return ResponseEntity.badRequest().body("手机号不能为空");
            }

            // 2. 校验文件是否为空
            if (mainImg.isEmpty() || listImg.isEmpty()) {
                return ResponseEntity.badRequest().body("请上传主图和列表图");
            }

            // 3. 校验文件类型（可选）
            if (!isValidImageType(mainImg) || !isValidImageType(listImg)) {
                return ResponseEntity.badRequest().body("仅支持JPG/PNG格式图片");
            }

            // 4. 保存数据
            Technician technician = new Technician();
            technician.setName(name);
            technician.setPhone(phone);
            technician.setMessage(message);

            Technician saved = technicianService.saveTechnician(technician, mainImg, listImg);
            return ResponseEntity.ok(saved);  // 修正拼写：oK → ok

        } catch (MaxUploadSizeExceededException e) {
            return ResponseEntity.badRequest().body("文件大小超过限制");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("服务器错误: " + e.getMessage());  // 修正语法错误
        }
    }

    // 校验图片类型（示例）
    private boolean isValidImageType(MultipartFile file) {
        String contentType = file.getContentType();
        return contentType != null &&
                (contentType.equals("image/jpeg") || contentType.equals("image/png"));
    }

    // 文件访问接口
    @GetMapping("/image/{filename}")
    public ResponseEntity<byte[]> getImage(@PathVariable String filename) throws IOException {
        Path path = Paths.get(uploadDir, filename).normalize();

        // 安全校验：防止目录遍历攻击
        if (!path.startsWith(Paths.get(uploadDir).normalize())) {
            return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
        }

        if (!Files.exists(path)) {
            return ResponseEntity.notFound().build();
        }

        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(Files.probeContentType(path)))
                .body(Files.readAllBytes(path));
    }

    // 修改分页查询方法
    // 127.0.0.1:9001/api/technicians/list?pageNum=1&pageSize=5
    // 127.0.0.1:9001/api/technicians/list?pageNum=1&pageSize=5&name=周
    // log.debug("数据: {}", dataList);
    @GetMapping("/list")
    public PageInfo<Technician> pageList(
            TechnicianQuery query,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "12") Integer pageSize) {

        query.setStatus("1");//查询在首页显示的
        PageInfo<Technician> pageInfo = technicianService.getTechniciansByPage(query, pageNum, pageSize);
        return pageInfo;
    }

    //127.0.0.1:9001/api/technicians/1
    @GetMapping(value = "/{id}")
    public Map<String, Object> getInfo(@PathVariable int id) {
        Map<String, Object> map = new HashMap<String, Object>();
        Technician t = technicianService.selectById(id);
        map.put("msg", "操作成功");
        map.put("code", 200);
        map.put("data", t);
        return map;
    }
}